package com.zywl.web.controller.sys;

import com.zywl.core.beans.AssResRel;
import com.zywl.core.beans.Company;
import com.zywl.core.beans.Member;
import com.zywl.core.beans.User;
import com.zywl.service.AssResRelService;
import com.zywl.service.CompanyService;
import com.zywl.service.MemberService;
import com.zywl.service.UserService;
import com.zywl.utils.models.AjaxResult;
import com.zywl.utils.models.PageData;
import com.zywl.utils.models.PageResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.MapUtil;
import com.zywl.utils.utils.enums.LogTypeEnum;
import com.zywl.web.controller.base.BaseController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.channels.MembershipKey;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/company")
public class CompanyController extends BaseController {
    @Autowired
    private CompanyService companyService;
    @Autowired
    private MemberService memberService;

    @GetMapping("/companyListPage")
    public ModelAndView companyListPage() {
        ModelAndView mav = new ModelAndView("company/companyListPage");
        return mav;
    }


    @PostMapping("/getCompanyList")
    public PageResult getCompanyList(HttpServletRequest request, PageData pageData) {

        Map<String, Object> condition = MapUtil.changeMap(request.getParameterMap());
        PageResult pageResult = null;
        try {
            pageResult = putToResult(companyService.getPageInfo(condition, pageData));
        } catch (Exception e) {
            logger.error("获取公司列表异常", e);
        }
        return pageResult;
    }

    @GetMapping("/companySubmitPage")
    public ModelAndView companySubmitPage(String id, HttpSession session) {
        ModelAndView mav = new ModelAndView("company/companySubmitPage");
        try {
            if (StringUtils.isNotEmpty(id)) {
                Company company = companyService.getById(Long.parseLong(id));
                mav.addObject("company", company);
            }
        } catch (Exception e) {
            logger.error("获取数据异常", e);
        }
        return mav;
    }

    @PostMapping("/companySubmit")
    public AjaxResult companySubmit(HttpServletRequest request, Company form) {
        AjaxResult ar = new AjaxResult();
        if (form != null) {
            Company company = null;
            String old = null;
            Date date = new Date();
            try {
                if (form.getComId() != null) {
                    company = companyService.getById(form.getComId());
                    old = company.getComName();
                    company.setComType(form.getComType());
                    company.setComName(form.getComName());
                    company.setComLinkman(form.getComLinkman());
                    company.setComMobile(form.getComMobile());
                    company.setComAddress(form.getComAddress());
                } else {
                    company = new Company();
                    form.setComStt("0");
                    form.setComCreateTime(date);
                    form.setComModifyTime(date);
                    if(StringUtils.isNotEmpty(form.getComIndustry())){
                        form.setComIndustry(","+form.getComIndustry()+",");
                    }
                    if(StringUtils.isNotEmpty(form.getComTag())){
                        form.setComTag(","+form.getComTag()+",");
                    }

                    User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
                    if (user.getUsrAssociationId() != null){
                        form.setComAssociationId(user.getUsrAssociationId());
                    }else{
                        ar.error("平台管理员无法帮忙创建公司");
                        return ar;
                    }

                    //查询公司名称是否已存在
                    Map<String, Object> condition = new HashMap<>();
                    condition.put("comName",form.getComName());
                    condition.put("comStt","0");
                    int count = companyService.getCountByParams(condition);
                    if(count > 0){
                        ar.error("该公司已存在，请修改");
                        return ar;
                    }
                    //查询该公司的负责人号码是否已经存在
                    condition = new HashMap<>();
                    condition.put("mebUsername",form.getComMobile());
                    condition.put("mebStt","0");
                    count = memberService.getCountByParams(condition);
                    if(count > 0){
                        ar.error("该号码作为账户已存在，请修改");
                        return ar;
                    }
                    BeanUtils.copyProperties(form, company);
                }

                if (form.getComId() == null) {
                    companyService.save(company);
                } else {
                    companyService.update(company);
                }
            } catch (Exception e) {
                logger.error("提交公司信息异常", e);
                ar.error("提交公司信息异常", e);
                return ar;
            }

            if (form.getComId() == null) {
                saveLog(request, LogTypeEnum.COMPANY.getKey(), "公司新增-" + form.getComName());
                ar.success("新增成功");
            } else if (old != null && !old.equals(form.getComName())) {
                saveLog(request, LogTypeEnum.COMPANY.getKey(), "公司修改-" + old + "→" + form.getComName());
                ar.success("修改成功");
            } else {
                saveLog(request, LogTypeEnum.COMPANY.getKey(), "公司修改-" + form.getComName());
                ar.success("修改成功");
            }
        } else {
            ar.error("提交失败，参数为空");
        }
        return ar;
    }

    @PostMapping("/companyDelete")
    public AjaxResult companyDelete(HttpServletRequest request, Long id) {
        AjaxResult ar = new AjaxResult();
        try {
            Company company = companyService.getById(id);
            String companyNickName = company.getComName();
            company.setComStt("1");
            companyService.update(company);//逻辑删除用户
            saveLog(request, LogTypeEnum.COMPANY.getKey(), "公司删除-" + companyNickName);
            ar.success("删除成功");
        } catch (Exception e) {
            ar.error("删除公司异常", e);
            logger.error("删除公司异常", e);
        }
        return ar;
    }

    @PostMapping("/updateState")
    public AjaxResult updateState(HttpServletRequest request, Long id,String stt) {
        AjaxResult ar = new AjaxResult();
        try {
            Company company = companyService.getById(id);
            String companyNickName = company.getComName();
            company.setComStt(stt);
            companyService.update(company);
            if("0".equals(stt)){
                saveLog(request, LogTypeEnum.COMPANY.getKey(), "公司启用-" + companyNickName);
            }else{
                saveLog(request, LogTypeEnum.COMPANY.getKey(), "公司禁用-" + companyNickName);
            }
            ar.success("操作成功");
        } catch (Exception e) {
            ar.error("操作公司异常", e);
            logger.error("操作公司异常", e);
        }
        return ar;
    }
}
